﻿using CommunityToolkit.Mvvm.ComponentModel;
using Company.Core.Helpers;
using Company.Core.Logger;
using Company.Database.Entities;
using Company.Plc;
using Company.Shell.Enums;
using Company.Shell.Extensions;
using Company.Shell.Interfaces;
using LiveCharts;
using LiveCharts.Defaults;
using System.Collections;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text;


namespace Company.Shell.Models
{
    /// <summary>
    /// 表示一个房间
    /// </summary>
    public class RoomEntity : ObservableObject
    {
        public event Action<AlarmEntity> OnAlarm;
        public IPlc Plc { get;  }

        private IConfigProvider ConfigProvider { get; }
        private RoomEntity() { }

        public RoomEntity(IPlc plc, IConfigProvider configProvider)
        {
            Plc = plc ?? throw new ArgumentNullException(nameof(plc));
            ConfigProvider = configProvider ?? throw new ArgumentNullException(nameof(configProvider));
            Init();
            Alarm();
        }
        /// <summary>
        /// 开启房间报警线程
        /// </summary>
        
        private void Alarm()
        {
            Task.Run(() =>
            {
                Thread.Sleep(1000);
                while (true)
                {
                    DoAlarm(27, Value27.OriginValue);
                    DoAlarm(28, Value28.OriginValue);
                    DoAlarm(29, Value29.OriginValue);
                    Thread.Sleep(1000);
                }
                
            });

        }
        /// <summary>
        /// 处理寄存器报警逻辑
        /// </summary>
        /// <param name="addressNumber"></param>
        /// <param name="value"></param>
        private void DoAlarm(int addressNumber, ushort value)
        {
            //27 -> 27.00 27.01 27.15
            BitArray array = new(BitConverter.GetBytes(value));
            for (int i = 0; i < array.Length; i++)
            {
                string address = AlarmItem.GetAddress(addressNumber, i);//27.00
                if (array[i] == true)
                {
                    var entity = AlarmEntities.FirstOrDefault(a => a.AddressNumber == address && a.Status == 1);//已经存在且未恢复
                    if (entity == null)//不存在，新增
                    {
                        AlarmEntity alarm = new()
                        {
                            Id = 0, // 显式设置为 0，让数据库自动生成
                            RoomNumber = Id,
                            AddressNumber = address,
                            AlarmTime = DateTime.Now,
                            Status = 1
                        };
                        //报警描述
                        AlarmItem alarmItem = ConfigProvider.AlarmItems.FirstOrDefault(a => a.Address == address);
                        if (alarmItem != null)
                        {
                            alarm.Message = alarmItem.Description;
                        }
                        else
                        {
                            alarm.Message = $"地址 {address} 报警";
                        }
                        
                        try
                        {
                            //显示到UI层
                            System.Windows.Application.Current?.Dispatcher.Invoke(() =>
                            {
                                AlarmEntities.Add(alarm);
                                
                                // 添加详细的调试信息
                                System.Diagnostics.Debug.WriteLine($"房间 {Id} 添加报警: {address} - {alarm.Message}");
                                System.Diagnostics.Debug.WriteLine($"房间 {Id} 当前报警总数: {AlarmEntities.Count}");
                                
                                // 触发属性变更通知，确保UI更新
                                OnPropertyChanged(nameof(AlarmEntities));
                            });
                            
                            // 触发事件以保存到数据库
                            OnAlarm?.Invoke(alarm);
                        }
                        catch (Exception ex)
                        {
                            Logs.Error(ex);
                        }
                    }
                }
                else
                {
                    //等于false，表示报警恢复,判断当前记录是否在AlarmEntities中，如果存在且状态为1，更新状态为0
                    //表示已经恢复，写入数据库中
                    var entity = AlarmEntities.FirstOrDefault(a => a.AddressNumber == address && a.Status == 1);
                    if (entity != null)
                    {
                        entity.Status = 0;
                        //从当前报警UI列表中移除
                        System.Windows.Application.Current?.Dispatcher.Invoke(() =>
                        {
                            AlarmEntities.Remove(entity);
                            System.Diagnostics.Debug.WriteLine($"房间 {Id} 移除报警: {address}");
                            System.Diagnostics.Debug.WriteLine($"房间 {Id} 剩余报警总数: {AlarmEntities.Count}");
                            
                            // 触发属性变更通知
                            OnPropertyChanged(nameof(AlarmEntities));
                        });
                        OnAlarm?.Invoke(entity);//通知UI层,写入数据库
                    }
                }
            }
        }

        private void Init()
        {
            // 使用反射自动添加所有 ValueX 属性
            var valueProperties = this.GetType()
                .GetProperties()
                .Where(p => p.Name.StartsWith("Value") && p.PropertyType == typeof(PlcValue))
                .OrderBy(p => {
                    var numberPart = p.Name.Substring(5); // 移除 "Value" 前缀
                    return int.TryParse(numberPart, out int number) ? number : int.MaxValue;
                });

            foreach (var property in valueProperties)
            {
                var value = property.GetValue(this) as PlcValue;
                if (value != null)
                {
                    Values.Add(value);
                }
            }
        }

        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        /// <summary>
        /// 房间D区寄存器起始地址，每个房间100个寄存器
        /// </summary>
        public ushort Address { get; set; } = 1000;

        private ProgramEntity? program;
        public ProgramEntity? Program
        {
            get => program;
            set
            {
                SetProperty(ref program, value);
                SetEnable((roomMode, value));
            }
        }

        /// <summary>
        /// 房间运行状态
        /// </summary>
        private RoomMode roomMode = RoomMode.Stopping;
        public RoomMode RoomMode
        {
            get => roomMode;
            set
            {
                SetProperty(ref roomMode, value);
                SetEnable((value, Program));
            }
        }

        /// <summary>
        /// 设置按钮可用状态
        /// </summary>
        /// <param name="p"></param>
        private void SetEnable((RoomMode, ProgramEntity)? p)
        {
            if (p.Value.Item2 == null || p.Value.Item1 == RoomMode.Stopping)
            {
                IsEnabled = false;
            }
            else
            {
                IsEnabled = true;
            }
        }
        private RoomParameter roomParameter = new();
        /// <summary>
        /// 房间参数
        /// </summary>
        public RoomParameter RoomParameter
        {
            get => roomParameter;
            set => SetProperty(ref roomParameter, value);
        }
        private DateTime startTime = DateTime.MinValue;
        public DateTime StartTime
        {
            get => startTime;
            set => SetProperty(ref startTime, value);
        }
        private DateTime endTime;
        public DateTime EndTime
        {
            get => endTime;
            set => SetProperty(ref endTime, value);
        }
        private TimeSpan totalTime;
        public TimeSpan TotalTime
        {
            get => totalTime;
            set => SetProperty(ref totalTime, value);
        }
        /// <summary>
        /// 房间运行百分比
        /// </summary>
        private double percent = 100;
        public double Percent
        {
            get => percent;
            set => SetProperty(ref percent, value);
        }
        /// <summary>
        /// 按钮是否可用
        /// </summary>
        private bool isEnabled = false;
        public bool IsEnabled
        {
            get => isEnabled;
            set => SetProperty(ref isEnabled, value);
        }
        private CacheEntity cache  = new ();
        /// <summary>
        /// 缓存数据
        /// </summary>
        public CacheEntity Cache
        {
            get => cache; 
            set => SetProperty(ref cache, value); 
        }

        private TimeSpan timeSpan = new();
        /// <summary>
        /// X轴时间在缓存中的偏移量
        /// </summary>
        public TimeSpan OffsetTime
        {
            get => timeSpan;
            set => SetProperty(ref timeSpan, value);
        }
        private ObservableCollection<AlarmEntity> alarmEntities = new();
        public ObservableCollection<AlarmEntity> AlarmEntities
        {
            get => alarmEntities;
            set => SetProperty(ref alarmEntities, value);
        }
        #region 12个数字量的曲线
        private ChartValues<ObservablePoint> line0 = new();
        public ChartValues<ObservablePoint> Line0
        {
            get => line0;
            set => SetProperty(ref line0, value);
        }

        private ChartValues<ObservablePoint> line1 = new();
        public ChartValues<ObservablePoint> Line1
        {
            get => line1;
            set => SetProperty(ref line1, value);
        }

        private ChartValues<ObservablePoint> line2 = new();
        public ChartValues<ObservablePoint> Line2
        {
            get => line2;
            set => SetProperty(ref line2, value);
        }

        private ChartValues<ObservablePoint> line3 = new();
        public ChartValues<ObservablePoint> Line3
        {
            get => line3;
            set => SetProperty(ref line3, value);
        }

        private ChartValues<ObservablePoint> line4 = new();
        public ChartValues<ObservablePoint> Line4
        {
            get => line4;
            set => SetProperty(ref line4, value);
        }

        private ChartValues<ObservablePoint> line5 = new();
        public ChartValues<ObservablePoint> Line5
        {
            get => line5;
            set => SetProperty(ref line5, value);
        }

        private ChartValues<ObservablePoint> line6 = new();
        public ChartValues<ObservablePoint> Line6
        {
            get => line6;
            set => SetProperty(ref line6, value);
        }

        private ChartValues<ObservablePoint> line7 = new();
        public ChartValues<ObservablePoint> Line7
        {
            get => line7;
            set => SetProperty(ref line7, value);
        }

        private ChartValues<ObservablePoint> line8 = new();
        public ChartValues<ObservablePoint> Line8
        {
            get => line8;
            set => SetProperty(ref line8, value);
        }

        private ChartValues<ObservablePoint> line9 = new();
        public ChartValues<ObservablePoint> Line9
        {
            get => line9;
            set => SetProperty(ref line9, value);
        }

        private ChartValues<ObservablePoint> line10 = new();
        public ChartValues<ObservablePoint> Line10
        {
            get => line10;
            set => SetProperty(ref line10, value);
        }

        private ChartValues<ObservablePoint> line11 = new();
        public ChartValues<ObservablePoint> Line11
        {
            get => line11;
            set => SetProperty(ref line11, value);
        }
        #endregion

        // 在 RoomEntity 类中替换现有的 Value0, Value1, Value2 为以下代码：
        #region
        public PlcValue Value0 { get; set; } = new PlcValue(0);
        public PlcValue Value1 { get; set; } = new PlcValue(1);
        public PlcValue Value2 { get; set; } = new PlcValue(2);
        public PlcValue Value3 { get; set; } = new PlcValue(3);
        public PlcValue Value4 { get; set; } = new PlcValue(4);
        public PlcValue Value5 { get; set; } = new PlcValue(5);
        public PlcValue Value6 { get; set; } = new PlcValue(6);
        public PlcValue Value7 { get; set; } = new PlcValue(7);
        public PlcValue Value8 { get; set; } = new PlcValue(8);
        public PlcValue Value9 { get; set; } = new PlcValue(9);
        public PlcValue Value10 { get; set; } = new PlcValue(10);
        public PlcValue Value11 { get; set; } = new PlcValue(11);
        public PlcValue Value12 { get; set; } = new PlcValue(12);
        public PlcValue Value13 { get; set; } = new PlcValue(13);
        public PlcValue Value14 { get; set; } = new PlcValue(14);
        public PlcValue Value15 { get; set; } = new PlcValue(15);
        public PlcValue Value16 { get; set; } = new PlcValue(16);
        public PlcValue Value17 { get; set; } = new PlcValue(17);
        public PlcValue Value18 { get; set; } = new PlcValue(18);
        public PlcValue Value19 { get; set; } = new PlcValue(19);
        public PlcValue Value20 { get; set; } = new PlcValue(20);
        public PlcValue Value21 { get; set; } = new PlcValue(21);
        public PlcValue Value22 { get; set; } = new PlcValue(22);
        public PlcValue Value23 { get; set; } = new PlcValue(23);
        public PlcValue Value24 { get; set; } = new PlcValue(24);
        public PlcValue Value25 { get; set; } = new PlcValue(25);
        public PlcValue Value26 { get; set; } = new PlcValue(26);
        public PlcValue Value27 { get; set; } = new PlcValue(27);
        public PlcValue Value28 { get; set; } = new PlcValue(28);
        public PlcValue Value29 { get; set; } = new PlcValue(29);
        public PlcValue Value30 { get; set; } = new PlcValue(30);
        public PlcValue Value31 { get; set; } = new PlcValue(31);
        public PlcValue Value32 { get; set; } = new PlcValue(32);
        public PlcValue Value33 { get; set; } = new PlcValue(33);
        public PlcValue Value34 { get; set; } = new PlcValue(34);
        public PlcValue Value35 { get; set; } = new PlcValue(35);
        public PlcValue Value36 { get; set; } = new PlcValue(36);
        public PlcValue Value37 { get; set; } = new PlcValue(37);
        public PlcValue Value38 { get; set; } = new PlcValue(38);
        public PlcValue Value39 { get; set; } = new PlcValue(39);
        public PlcValue Value40 { get; set; } = new PlcValue(40);
        public PlcValue Value41 { get; set; } = new PlcValue(41);
        public PlcValue Value42 { get; set; } = new PlcValue(42);
        public PlcValue Value43 { get; set; } = new PlcValue(43);
        public PlcValue Value44 { get; set; } = new PlcValue(44);
        public PlcValue Value45 { get; set; } = new PlcValue(45);
        public PlcValue Value46 { get; set; } = new PlcValue(46);
        public PlcValue Value47 { get; set; } = new PlcValue(47);
        public PlcValue Value48 { get; set; } = new PlcValue(48);
        public PlcValue Value49 { get; set; } = new PlcValue(49);
        public PlcValue Value50 { get; set; } = new PlcValue(50);
        public PlcValue Value51 { get; set; } = new PlcValue(51);
        public PlcValue Value52 { get; set; } = new PlcValue(52);
        public PlcValue Value53 { get; set; } = new PlcValue(53);
        public PlcValue Value54 { get; set; } = new PlcValue(54);
        public PlcValue Value55 { get; set; } = new PlcValue(55);
        public PlcValue Value56 { get; set; } = new PlcValue(56);
        public PlcValue Value57 { get; set; } = new PlcValue(57);
        public PlcValue Value58 { get; set; } = new PlcValue(58);
        public PlcValue Value59 { get; set; } = new PlcValue(59);
        public PlcValue Value60 { get; set; } = new PlcValue(60);
        public PlcValue Value61 { get; set; } = new PlcValue(61);
        public PlcValue Value62 { get; set; } = new PlcValue(62);
        public PlcValue Value63 { get; set; } = new PlcValue(63);
        public PlcValue Value64 { get; set; } = new PlcValue(64);
        public PlcValue Value65 { get; set; } = new PlcValue(65);
        public PlcValue Value66 { get; set; } = new PlcValue(66);
        public PlcValue Value67 { get; set; } = new PlcValue(67);
        public PlcValue Value68 { get; set; } = new PlcValue(68);
        public PlcValue Value69 { get; set; } = new PlcValue(69);
        public PlcValue Value70 { get; set; } = new PlcValue(70);
        public PlcValue Value71 { get; set; } = new PlcValue(71);
        public PlcValue Value72 { get; set; } = new PlcValue(72);
        public PlcValue Value73 { get; set; } = new PlcValue(73);
        public PlcValue Value74 { get; set; } = new PlcValue(74);
        public PlcValue Value75 { get; set; } = new PlcValue(75);
        public PlcValue Value76 { get; set; } = new PlcValue(76);
        public PlcValue Value77 { get; set; } = new PlcValue(77);
        public PlcValue Value78 { get; set; } = new PlcValue(78);
        public PlcValue Value79 { get; set; } = new PlcValue(79);
        public PlcValue Value80 { get; set; } = new PlcValue(80);
        public PlcValue Value81 { get; set; } = new PlcValue(81);
        public PlcValue Value82 { get; set; } = new PlcValue(82);
        public PlcValue Value83 { get; set; } = new PlcValue(83);
        public PlcValue Value84 { get; set; } = new PlcValue(84);
        public PlcValue Value85 { get; set; } = new PlcValue(85);
        public PlcValue Value86 { get; set; } = new PlcValue(86);
        public PlcValue Value87 { get; set; } = new PlcValue(87);
        public PlcValue Value88 { get; set; } = new PlcValue(88);
        public PlcValue Value89 { get; set; } = new PlcValue(89);
        public PlcValue Value90 { get; set; } = new PlcValue(90);
        public PlcValue Value91 { get; set; } = new PlcValue(91);
        public PlcValue Value92 { get; set; } = new PlcValue(92);
        public PlcValue Value93 { get; set; } = new PlcValue(93);
        public PlcValue Value94 { get; set; } = new PlcValue(94);
        public PlcValue Value95 { get; set; } = new PlcValue(95);
        public PlcValue Value96 { get; set; } = new PlcValue(96);
        public PlcValue Value97 { get; set; } = new PlcValue(97);
        public PlcValue Value98 { get; set; } = new PlcValue(98);
        public PlcValue Value99 { get; set; } = new PlcValue(99);

        public List<PlcValue> Values { get; set; } = new List<PlcValue>();
        #endregion
        ushort temperatureValue;
        ushort humidityValue;
        bool newCurve = false;
        /// <summary>
        /// 开始运行
        /// </summary>
        /// <returns></returns>
        public async Task RunAsync(DateTime? _startTime = null)
        {
            if (Program == null) return;
            //计算时间
            var temperatures = Program.Temperature as IList<ObservablePoint>;
            var humidities = Program.Humidities as IList<ObservablePoint>;
            ObservablePoint? temperature = temperatures.LastOrDefault();
            ObservablePoint? humidity = humidities.LastOrDefault();
            if (temperature == null || humidity == null) return;
            var minute = temperature.X > humidity.X ? temperature.X : humidity.X;//取最大时间
            var timespan = TimeSpan.FromMinutes(minute);
            TotalTime = timespan;
            StartTime = DateTime.Now;
            EndTime = StartTime+ TotalTime;
            Stopwatch stopwatch = new();
            Percent = 0;
            RoomMode = RoomMode.Running;

            //持续运行
            if (_startTime != null)
            {
                StartTime = _startTime.Value;
                EndTime = StartTime + TotalTime;
                TotalTime = timespan;
                OffsetTime = DateTime.Now - StartTime;//计算偏移量
                newCurve = false;
                //加载曲线
                await InitCurve();

            }
            else
            {
                //记录缓存
                Cache.StartTime = StartTime;
                Cache.ProgramName = Program.Name;
                Cache.RoomMode = RoomMode;
                OffsetTime = TimeSpan.Zero;
                newCurve = true;
            }


            await Task.Run(() =>
            {
                ThreadPool.QueueUserWorkItem(ShowCurve, stopwatch);//在线程池上运行子线程，子线程实时显示曲线
                ThreadPool.QueueUserWorkItem(SaveCurve, stopwatch);//在线程池上运行子线程，子线程实时保存曲线
                while (RoomMode != RoomMode.Stopping && DateTime.Now <= EndTime)
                {
                    var timespan = stopwatch.Elapsed;//已经运行的时间
                    temperatureValue = Program.Temperature.GetValue(timespan.TotalMinutes);
                    humidityValue = Program.Humidities.GetValue(timespan.TotalMinutes);
#if DEBUG
                    Percent = DateTime.Now.Second;//进度条
#else
                     Plc.Write($"{Address + 30}", temperatureValue);//写入温度预期值
                     Plc.Write($"{Address + 31}", humidityValue);//写入湿度预期值
                     Plc.Write($"{Address + 60}", RoomParameter.GetTemperatureParameters());//写入温度plc参数
                     Plc.Write($"{Address + 70}", RoomParameter.GetHumidityParameters());//写入湿度plc参数
                     Percent = (int)(timespan.TotalMinutes / TotalTime.TotalMinutes);//进度条
#endif

                    Thread.Sleep(1000);//每秒更新一次
                }
                if (DateTime.Now > EndTime)
                {
                    RoomMode = RoomMode = RoomMode.Stopping;
                    Cache.RoomMode = RoomMode;
                }

            });

        }
        //加载上次中断的曲线数据，显示到livecharts
        private Task InitCurve()
        {
            return Task.Run(() =>
            {
                var fullname = CurveHelper.GetLastCurveFullName(Id, startTime, Cache.CsvFileName);
                if (!File.Exists(fullname)) return;
                List<string> rows = [.. File.ReadAllLines(fullname, Encoding.UTF8)];
                if (rows.Count == 0) return;
                rows.RemoveAt(0);
                try
                {
                    // 使用反射获取所有 Line 属性
                    var lineProperties = this.GetType()
                        .GetProperties()
                        .Where(p => p.Name.StartsWith("Line") && p.PropertyType == typeof(ChartValues<ObservablePoint>))
                        .OrderBy(p => {
                            var numberPart = p.Name.Substring(4); // 移除 "Line" 前缀
                            return int.TryParse(numberPart, out int number) ? number : int.MaxValue;
                        })
                        .ToArray();
                    foreach (var row in rows)
                    {
                        string[] colums = row.Split('.');
                        if (colums == null || colums.Length == 0) continue;
                        var success = double.TryParse(colums[1], out double x);
                        if (!success) continue;

                        System.Windows.Application.Current.Dispatcher.Invoke(() =>
                        {
                            for (int i = 0; i < lineProperties.Length && i + 2 < colums.Length; i++)
                            {
                                if (double.TryParse(colums[i + 2], out double y))
                                {
                                    var point = new ObservablePoint(x, y);
                                    var chartValues = lineProperties[i].GetValue(this) as ChartValues<ObservablePoint>;
                                    chartValues?.Add(point);
                                }
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                    Logs.Error(ex);
                }
               
            });
        }

        /// <summary>
        /// 保存曲线到CSV文件
        /// </summary>
        /// <param name="state"></param>
        private void SaveCurve(object? state)
        {
            if (state is null) return;
            if (state is not Stopwatch stopwatch) return;
            string fullname = CurveHelper.GetCurveFullName(Id, StartTime, EndTime);//获取文件全路径
            string csvName = $"{StartTime:yyyyMMddHHmmss}_{EndTime:yyyyMMddHHmmss}";
            string column = $"序号,时间,{roomParameter.TitleLine0},{roomParameter.TitleLine1},{roomParameter.TitleLine2},{roomParameter.TitleLine3},{roomParameter.TitleLine4},{roomParameter.TitleLine5},{roomParameter.TitleLine6},{roomParameter.TitleLine7},{roomParameter.TitleLine8},{roomParameter.TitleLine9},{roomParameter.TitleLine10},{roomParameter.TitleLine11},温度,湿度{Environment.NewLine}";
            if (newCurve)//如果是新曲线，创建新文件
            {
                File.AppendAllText(fullname, column, Encoding.UTF8);
            } 
            File.AppendAllText(fullname, column, Encoding.UTF8);//写入列名
            Cache.CsvFileName = csvName;//记录缓存
            int index = 1;
            while (RoomMode == RoomMode.Running)
            {
                var timespan = stopwatch.Elapsed.Minutes + +OffsetTime.Minutes;//已经运行的时间
                string data = $"{index++},{timespan},{Values[0].Value},{Values[1].Value},{Values[2].Value}, {Values[3].Value}, {Values[4].Value},{Values[5].Value},{Values[6].Value},{Values[7].Value},{Values[8].Value},{Values[9].Value}, {Values[10].Value},{Values[11].Value},{temperatureValue/10.0},{humidityValue/10.0}{Environment.NewLine}";
                File.AppendAllText(fullname, data, Encoding.UTF8);//写入数据
                Cache.WriteTime = DateTime.Now;// 更新最后一次写数据的时间
                Thread.Sleep(1000);

            }
        }

        /// <summary>
        /// 显示曲线
        /// </summary>
        /// <param name="state"></param>

        private void ShowCurve(object? state)
        {
            if (state is null) return;
            if (state is not Stopwatch stopwatch) return;
            while(RoomMode == RoomMode.Running)
            {
                var timespan = stopwatch.Elapsed;//已经运行的时间
                System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    Line0.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[0].Value));
                    Line1.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[1].Value));
                    Line2.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[2].Value));
                    Line3.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[3].Value));
                    Line4.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[4].Value));
                    Line5.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[5].Value));
                    Line6.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[6].Value));
                    Line7.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[7].Value));
                    Line8.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[8].Value));
                    Line9.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[9].Value));
                    Line10.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[10].Value));
                    Line11.Add(new ObservablePoint(timespan.Minutes + OffsetTime.Minutes, Values[11].Value));
                }));
#if DEBUG
                Thread.Sleep(1000 );//每秒更新一次
#else
                 Thread.Sleep(1000 * 60 * 5);//每5分钟更新一次
#endif
            }

        }

        /// <summary> 
        /// 结束运行
        /// </summary>
        /// <returns></returns>
        public async Task StopAsync()
        {
            await Task.Run(() =>
            {
                RoomMode = RoomMode.Stopping;
                Cache.RoomMode = RoomMode;
            });
        }
        /// <summary>
        /// 解析100个点位
        /// </summary>
        /// <param name="array"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void Resolve(ushort[] array)
        {
            if (array == null || array.Length != 100)
            
                return;
                for (int i = 0; i < array.Length; i++)
                {
                    Values[i].OriginValue = array[i];
                    Values[i].Value = array[i] / 10.0;
#if DEBUG
                if(i == 18)
                {
                    Values[i].OriginValue = (ushort)(RoomMode == RoomMode.Running ? 1 : 0);
                    Values[i].Value = (ushort)(RoomMode == RoomMode.Running ? 1 : 0);
                }
                if (i == 30)
                {
                    Values[i].OriginValue = temperatureValue;
                    Values[i].Value = temperatureValue / 10.0;
                }
                if (i == 31)
                {
                    Values[i].OriginValue = humidityValue;
                    Values[i].Value = humidityValue / 10.0;
                }

#endif
            }
            
        }
    }
}
